package com.laxcen.smoke.service.impl;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.laxcen.smoke.dao.GetForSdkMessageDao;
import com.laxcen.smoke.service.GetForSdkMessageService;
import com.laxcen.smoke.test.AmqpJavaClientDemo;
import com.laxcen.smoke.util.DBUtils;
import com.laxcen.smoke.util.Response;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class GetForSdkMessageServiceimpl implements GetForSdkMessageService, CommandLineRunner {


    @Value("${accessKey}")
    private String accessKey;

    @Value("${accessSecret}")
    private String accessSecret;

    @Value("${productkey}")
    private String ProductKey;


    @Value("${consumerGroupId}")
    private String consumerGroupId;

    @Value("${clientId}")
    private String clientId;

    @Value("${connectionUrl}")
    private String connectionUrl;


    @Autowired
    private GetForSdkMessageDao getForSdkMessageDao;

    private static GetForSdkMessageServiceimpl getForSdkMessageServiceimpl;

    @PostConstruct
    public void init() {
        getForSdkMessageServiceimpl = this;
        getForSdkMessageServiceimpl.getForSdkMessageDao = this.getForSdkMessageDao;
    }


    private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class);

    //业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
    private final static ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue(50000));

    @Override
    public Response insert() throws Exception {
        //参数说明，请参见AMQP客户端接入说明文档。
//        String accessKey = "LTAI5tQqhoe1XSrkoCWkDDQ9";
//        String accessSecret = "MXycRe3SmNlDPKuLNt1cfxhFyjk5Cf";
//        String consumerGroupId = "DEFAULT_GROUP";
        //iotInstanceId：企业版实例请填写实例ID，公共实例请填空字符串""。
        String iotInstanceId = "";
        long timeStamp = System.currentTimeMillis();
        //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
        String signMethod = "hmacsha1";
        //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。
        //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
        String clientId = "Test001";

        //userName组装方法，请参见AMQP客户端接入说明文档。
        String userName = clientId + "|authMode=aksign"
                + ",signMethod=" + signMethod
                + ",timestamp=" + timeStamp
                + ",authId=" + accessKey
                + ",iotInstanceId=" + iotInstanceId
                + ",consumerGroupId=" + consumerGroupId
                + "|";
        //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
        String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
        String password = doSign(signContent,accessSecret, signMethod);
        //${YourHost}为接入域名，请参见AMQP客户端接入说明文档。
        String connectionUrl = "failover:(amqps://1070277949580075.iot-amqp.cn-shanghai.aliyuncs.com:5671?amqp.idleTimeout=80000)"
                + "?failover.reconnectDelay=30";

        Hashtable<String, String> hashtable = new Hashtable<>();
        hashtable.put("connectionfactory.SBCF",connectionUrl);
        hashtable.put("queue.QUEUE", "default");
        hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        Context context = new InitialContext(hashtable);
        ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF");
        Destination queue = (Destination)context.lookup("QUEUE");
        // 创建连接。
        Connection connection = cf.createConnection(userName, password);
        ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
        // 创建会话。
        // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
        // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        // 创建Receiver连接。
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(messageListener);

        return null;
    }

    private static MessageListener messageListener = new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                //1.收到消息之后一定要ACK。
                // 推荐做法：创建Session选择Session.AUTO_ACKNOWLEDGE，这里会自动ACK。
                // 其他做法：创建Session选择Session.CLIENT_ACKNOWLEDGE，这里一定要调message.acknowledge()来ACK。
                // message.acknowledge();
                //2.建议异步处理收到的消息，确保onMessage函数里没有耗时逻辑。
                // 如果业务处理耗时过程过长阻塞住线程，可能会影响SDK收到消息后的正常回调。
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        processMessage(message);
                    }
                });
            } catch (Exception e) {
                logger.error("submit task occurs exception ", e);
            }
        }
    };

    /**
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private static void processMessage(Message message) {
        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            long ids = DBUtils.nextId();
            String id = String.valueOf(ids);
            getForSdkMessageServiceimpl.getForSdkMessageDao.insert(id, topic, messageId, content, 0, new Date());

            //获取设备编号用于监听事件轮询
            List<String> list = getForSdkMessageServiceimpl.getForSdkMessageDao.getSmartNo();

            // 解析处理从iot中content拿到的数据
            JSONObject json = JSONObject.fromObject(content);
//            String name = json.getString("name");
//            if (json.getString("identifier")!=null) {
//            String productkey = json.getString("productKey");
//            if (productkey.equals("a1VQrWIUFTW")){
//            if (productkey.equals("a1ZzC2gZ1fp")){
                if (json.has("identifier")) {
                    String identifier = json.getString("identifier");
                    String value = json.getString("value");
                    //监听获取广告事件
                    if ("GetAdv".equals(identifier)) {
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject jsonob = JSONObject.fromObject(value);
                            String smartno = jsonob.getString("DeviceNo");//智能柜编号
                            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tQqhoe1XSrkoCWkDDQ9", "MXycRe3SmNlDPKuLNt1cfxhFyjk5Cf");
                            DefaultAcsClient client = new DefaultAcsClient(profile);
                            InvokeThingServiceRequest request = new InvokeThingServiceRequest();
                            String adver = getForSdkMessageServiceimpl.getForSdkMessageDao.getAdverBySmartNo();
                            if (adver.contains(",")) {
                                String[] sfarray = adver.split(",");
                                ArrayList arrayList = new ArrayList();
                                String s = "";
                                StringBuffer sb = new StringBuffer();

                                for (int j = 0; j < sfarray.length; j++) {
                                    arrayList.add(j, "\"" + sfarray[j] + "\"");
                                    s = "{\"Url\":" + arrayList.get(j) + "}";
                                    if (sb.length() == 0) {
                                        sb.append(s);
                                    } else if (sb.length() != 0) {
                                        sb.append("," + s);
                                    }
                                }
                                String param = "{\"PicUrl\":[" + sb + "]}";
                                request.setArgs(param);

                            } else {
                                String param = adver;
                                request.setArgs(param);

                            }
                            request.setIdentifier("Advertisement");
                            //TODO
                            request.setProductKey("a1ZzC2gZ1fp");
//                            request.setProductKey("a1VQrWIUFTW");
                            request.setDeviceName(list.get(i));
                            try {
                                InvokeThingServiceResponse response = client.getAcsResponse(request);
                                System.out.println(response.getData());
                                System.out.println(response.getSuccess());
                                System.out.println(response.getErrorMessage());
                            } catch (ServerException e) {
                                e.printStackTrace();
                            } catch (ClientException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //iot存货结果
                    else if ("UpOrderStockResult".equals(identifier)) {
                        JSONObject jsonob = JSONObject.fromObject(value);
                        String smartno = jsonob.getString("DeviceNo");//智能柜编号
                        String userid = jsonob.getString("UserId");//用户id
                        String orderno = jsonob.getString("OrderNo");//订单编号
                        String boxes = jsonob.getString("Boxes");//格子信息
                        JSONArray jsonArr = JSONArray.fromObject(boxes);
//                String box = boxes.replaceAll("\\[","").replaceAll("\\]","");
//                JSONObject jsonbox = JSONObject.fromObject(box);
                        String string[] = new String[jsonArr.size()];
                        for (int i = 0; i < jsonArr.size(); i++) {
                            string[i] = jsonArr.get(i).toString();
                            JSONObject jjs = JSONObject.fromObject(string[i]);
                            String boxno = jjs.getString("BoxNo");//格子编号
                            String opertime = jjs.getString("OperateTime");//操作时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateopertime = "";
                            Long opertm = Long.valueOf(opertime);
                            dateopertime = sdf.format(opertm);
                            Date realtime = sdf.parse(dateopertime);
//                        String isnullid = getForSdkMessageServiceimpl.getForSdkMessageDao.getIdByDis(smartno, boxno, orderno);
//                    if (isnullid != null || !"".equals(isnullid)) {
//                        return;
//                    } else {
//                        if (isnullid == null) {
                            //插入操作订单表操作
                            long orderids = DBUtils.nextId();
                            String orderid = String.valueOf(orderids);
//                            String opname = getForSdkMessageServiceimpl.getForSdkMessageDao.getIdFromUser(userid);
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertuporder(orderid, smartno, boxno, userid, realtime, 0, orderno, new Date());
                            long orderdetailids = DBUtils.nextId();
                            String orderdetailid = String.valueOf(orderdetailids);
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertuporderdetail(orderdetailid, orderid, smartno, boxno, realtime, 0, 0, new Date());
                            //修改格子状态为占用 2
                            //获取格子id
                            List<String> boxidlist = getForSdkMessageServiceimpl.getForSdkMessageDao.getBoxIdBySmartNoAndBoxNo(smartno, boxno);
                            for (int j = 0; j < boxidlist.size(); j++) {
                                getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoxStatusGL(2, boxidlist.get(j));
                            }
                        }
                        //iot取货结果
                    } else if ("UpOrderPickResult".equals(identifier)) {
                        JSONObject jsonob = JSONObject.fromObject(value);
                        String smartno = jsonob.getString("DeviceNo");//智能柜编号
                        String userid = jsonob.getString("UserId");//用户id
                        String orderno = jsonob.getString("OrderNo");//订单编号
                        String boxes = jsonob.getString("Boxes");//格子信息
                        JSONArray jsonArr = JSONArray.fromObject(boxes);
                        String string[] = new String[jsonArr.size()];
                        for (int i = 0; i < jsonArr.size(); i++) {
                            string[i] = jsonArr.get(i).toString();
                            JSONObject jjs = JSONObject.fromObject(string[i]);
                            String boxno = jjs.getString("BoxNo");//格子编号
                            String opertime = jjs.getString("OperateTime");//操作时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateopertime = "";
                            Long opertm = Long.valueOf(opertime);
                            dateopertime = sdf.format(opertm);
                            Date realtime = sdf.parse(dateopertime);
                            //插入操作订单表操作
                            long orderids = DBUtils.nextId();
                            String orderid = String.valueOf(orderids);
//                        String opname = getForSdkMessageServiceimpl.getForSdkMessageDao.getIdFromUser(userid);
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertuporder(orderid, smartno, boxno, userid, realtime, 1, orderno, new Date());
                            long orderdetailids = DBUtils.nextId();
                            String orderdetailid = String.valueOf(orderdetailids);
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertuporderdetail(orderdetailid, orderid, smartno, boxno, realtime, 1, 1, new Date());
                            //修改格子状态为正常 1
//                        //获取格子id
//                        List<String> boxidlist = getForSdkMessageServiceimpl.getForSdkMessageDao.getBoxIdBySmartNoAndBoxNo(smartno,boxno);
//                        //修改格子表格子状态
//                        for (int k = 0; k < boxidlist.size();k++) {
//                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoxStatus(2,boxidlist.get(k));
//                        }
                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoxStatus(1, smartno, boxno);
                        }
                    }//告警异常
                    else if ("AbnormalAlarm".equals(identifier)) {
                        JSONObject jsonob = JSONObject.fromObject(value);
                        String smartno = jsonob.getString("DeviceNo");//智能柜编号
                        String alarmtype = jsonob.getString("AlarmType");//告警类型
                        int alarmrealtype = Integer.valueOf(alarmtype);
                        String alarmbox = jsonob.getString("AlarmContent");
                        if (!alarmbox.contains("号")) {
//                    if (null==sresult){
                            //插入异常表
                            long anormalids = DBUtils.nextId();
                            String anormalid = String.valueOf(anormalids);
                            String alarmcontent = jsonob.getString("AlarmContent");//告警content维修用
                            String opertime = json.getString("time");//操作时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateopertime = "";
                            Long opertm = Long.valueOf(opertime);
                            dateopertime = sdf.format(opertm);
                            Date realtime = sdf.parse(dateopertime);
                            //修改智能柜状态
//                        getForSdkMessageServiceimpl.getForSdkMessageDao.updateSmartByNo(1,smartno);
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertannormalNullBox(anormalid, smartno, alarmrealtype, realtime, alarmcontent, 1);
                        } else {
                            String sresult = alarmbox.substring(0, alarmbox.indexOf("号"));
                            int insre = Integer.valueOf(sresult);
                            String realin = "";
                            realin = String.valueOf(insre);//格子编号
                            String alarmcontent = jsonob.getString("AlarmContent");//告警content维修用
                            String opertime = json.getString("time");//操作时间
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateopertime = "";
                            Long opertm = Long.valueOf(opertime);
                            dateopertime = sdf.format(opertm);
                            Date realtime = sdf.parse(dateopertime);
                            //插入异常表操作
                            long anormalids = DBUtils.nextId();
                            String anormalid = String.valueOf(anormalids);
                            //获取格子id
                            List<String> boxidlist = getForSdkMessageServiceimpl.getForSdkMessageDao.getBoxIdBySmartNoAndBoxNo(smartno, realin);
                            //获取实体柜id
                            List<String> boardidlist = getForSdkMessageServiceimpl.getForSdkMessageDao.getBoardIdBySmartNoAndBoxNo(smartno, realin);
                            //修改格子表格子状态
                            for (int i = 0; i < boxidlist.size(); i++) {
                                getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoxStatusGL(3, boxidlist.get(i));
                            }
                            //修改实体柜状态
                            for (int k = 0; k < boardidlist.size(); k++) {
                                getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoardStatusGL(1, boardidlist.get(k));
                            }
                            //修改智能柜状态
//                        getForSdkMessageServiceimpl.getForSdkMessageDao.updateSmartByNo(1, smartno);
                            //插入异常表
                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertannormal(anormalid, smartno, realin, alarmrealtype, realtime, alarmcontent, 1);
                        }
                        //iot监控视频
                    } else if ("UpOperateVideo".equals(identifier)) {
                        JSONObject jsonob = JSONObject.fromObject(value);
                        String smartno = jsonob.getString("DeviceNo");//智能柜编号
                        String OperatorId = jsonob.getString("OperatorId");//操作人id
                        String operatetype = jsonob.getString("OperateType");
                        String VideoStruct = jsonob.getString("VideoStruct");//视频相关信息
                        JSONObject jsonvideo = JSONObject.fromObject(VideoStruct);
                        String video = jsonvideo.getString("Video");//操作视频
                        String accessKey = "LTAI5tQqhoe1XSrkoCWkDDQ9";
                        String accessSecret = "MXycRe3SmNlDPKuLNt1cfxhFyjk5Cf";
//                    IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
                        if (video.contains("raw")) {
                            OSSClient ossClient = new OSSClient("http://oss-cn-hangzhou.aliyuncs.com", accessKey,
                                    accessSecret);
                            // 设置URL过期时间为1年
//                        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                            Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24 * 30 * 12);
                            String realurl = video.substring(video.lastIndexOf("/"), video.length());
                            String uuurl = "convert_video" + realurl;
                            URL url = ossClient.generatePresignedUrl("iot-resource", uuurl, expiration, HttpMethod.GET);
                            String orderno = jsonvideo.getString("OrderNo");//订单号
                            String[] orderarr = orderno.split(",");
                            if (video.contains("_L")) {
                                //插入左摄像头监控数据
                                for (int i = 0; i < orderarr.length; i++) {
                                    if (null == operatetype) {
                                        getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoleft(url.toString(), orderarr[i], smartno, OperatorId, 0);
                                    } else {
                                        if (operatetype.equals("1")) {
                                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoleft(url.toString(), orderarr[i], smartno, OperatorId, 0);
                                        } else if (operatetype.equals("2")) {
                                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoleft(url.toString(), orderarr[i], smartno, OperatorId, 1);
                                        }
                                    }
                                }
                            }
                            if (video.contains("_R")) {
                                //插入右摄像头监控数据
                                for (int i = 0; i < orderarr.length; i++) {
                                    if (null == operatetype) {
                                        getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoright(url.toString(), orderarr[i], smartno, OperatorId, 0);
                                    } else {
                                        if (operatetype.equals("1")) {
                                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoright(url.toString(), orderarr[i], smartno, OperatorId, 0);
                                        } else if (operatetype.equals("2")) {
                                            getForSdkMessageServiceimpl.getForSdkMessageDao.insertopervideoright(url.toString(), orderarr[i], smartno, OperatorId, 1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //监听设备信息心跳事件
                    else if ("UpDeviceInfo".equals(identifier)) {
                        JSONObject jsonod = JSONObject.fromObject(value);
                        String smartno = jsonod.getString("DeviceNo");//设备编号
                        String UpsElectricity = jsonod.getString("UpsElectricity");//UPS电量
                        String UpsState = jsonod.getString("UpsState");//UPS状态
                        String boxes = jsonod.getString("Boxes");//格子信息
                        if (jsonod.containsKey("Version")) {
                            String version = jsonod.getString("Version");//版本号
                            //更新当前智能柜编号的版本号
                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateVersionIdBySmNo(getForSdkMessageServiceimpl.getForSdkMessageDao.getVersionIdByVersionNo(version), smartno);
                            //更新APP升级状态表
                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateissuestatus(version, smartno);
                            String localversion = getForSdkMessageServiceimpl.getForSdkMessageDao.getlocalversion(smartno);
                            String newversion = getForSdkMessageServiceimpl.getForSdkMessageDao.getnewversion(smartno);
                            if (null != localversion) {
                                if (localversion.equals(newversion)) {
                                    getForSdkMessageServiceimpl.getForSdkMessageDao.updateissstatus(1, smartno);
                                }
                            }
                        }
                        JSONArray jsonArr = JSONArray.fromObject(boxes);
                        String string[] = new String[jsonArr.size()];
                        for (int i = 0; i < jsonArr.size(); i++) {
                            string[i] = jsonArr.get(i).toString();
                            JSONObject jjs = JSONObject.fromObject(string[i]);
                            String boxno = jjs.getString("BoxNo");//格子编号
                            String boxstate = jjs.getString("BoxState");//格子状态
                            //格子状态
                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateBoxStatus(Integer.valueOf(boxstate), smartno, boxno);
                        }
                        List<String> boardid = getForSdkMessageServiceimpl.getForSdkMessageDao.getSmartboardidBySmartNo(smartno);
                        for (int z = 0; z < boardid.size(); z++) {
                            getForSdkMessageServiceimpl.getForSdkMessageDao.updateUpsForSmart(Integer.valueOf(UpsState), UpsElectricity, boardid.get(z));
                        }
//        获取已经存在的智能柜编号
                        List<String> abNormalRecord = getForSdkMessageServiceimpl.getForSdkMessageDao.getAbn();
                        for (int i = 0; i < abNormalRecord.size(); i++) {
                            // 查询主副柜、格子表是否有异常
                            List<String> listss = getForSdkMessageServiceimpl.getForSdkMessageDao.getNotState(abNormalRecord.get(i), 3);
                            if (listss.size() == 0) {
                                //修改智能柜表状态信息
//                intelligentMonitorDao.updateSmartByNo(0, abNormalRecord.get(i));
                                //修改主柜状态信息
//                intelligentMonitorDao.updateSmartBoardByNo(0,abNormalRecord.get(i));
                                List<String> idlist = getForSdkMessageServiceimpl.getForSdkMessageDao.getIdBySmartno(abNormalRecord.get(i), 3);
                                for (int j = 0; j < idlist.size(); j++) {
                                    //修改实体柜表状态信息
                                    getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartBoardBy(0, abNormalRecord.get(i), idlist.get(j));
                                }
                            }
                        }
                    }
                }
            if (!json.has("identifier")) {
                //处理设备离线添加到异常表中
                if (json.has("lastTime")) {
                    String status = json.getString("status");
                    String smartno = json.getString("deviceName");
                    //插入到异常表中设备离线
                    if ("offline".equals(status)) {
                        getForSdkMessageServiceimpl.getForSdkMessageDao.insertannormal(String.valueOf(DBUtils.nextId()), smartno, null, 6, new Date(), "设备离线", 1);
                        getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartstatus(smartno, 1);

                        getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartboard(getForSdkMessageServiceimpl.getForSdkMessageDao.getsmartboardid(smartno), 1);

                    }
                    if ("online".equals(status)) {
                        getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartstatus(smartno, 0);

                        getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartboard(getForSdkMessageServiceimpl.getForSdkMessageDao.getsmartboardid(smartno), 0);
                    }
                }

//           }else if (!json.has("identifier")){
//               //处理设备上线更新智能柜状态
//               if (json.has("lastTime")){
//                   String status = json.getString("status");
//                   String smartno = json.getString("deviceName");
//                   if ("online".equals(status)) {
//                       getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartstatus(smartno,0);
//
//                       getForSdkMessageServiceimpl.getForSdkMessageDao.updatesmartboard(getForSdkMessageServiceimpl.getForSdkMessageDao.getsmartboardid(smartno),0);
//                   }
//               }

            }
//        }
                logger.info("receive message"
                    + ",\n topic = " + topic
                    + ",\n messageId = " + messageId
                    + ",\n content = " + content);
        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }

    private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {}

        @Override
        public void onSessionClosed(Session session, Throwable cause) {}

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {}

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {}
    };

    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }

    //项目启动后自动运行run方法里面的代码
    @Override
    public void run(String... args) throws Exception {
        System.out.println("执行接入SDK从iot中拿到的数据插入数据库操作");
        insert();
    }
}
